package Package;
import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * Class FileXml.
 * @author Ingrid Campos
 * @author Sandra Calderon
 * */
public class FileXml {

	DocumentBuilderFactory factory;
	DocumentBuilder db;
	Document doc;
	/**
	 * Constructor
	 * */
	public FileXml() throws ParserConfigurationException{
		factory= DocumentBuilderFactory.newInstance();
		db=factory.newDocumentBuilder();
	}
	
	/**
	 * read file
	 * @param myFile
	 * */
	public void read(String myFile) throws SAXException, IOException{
		doc=db.parse(new File(myFile));
		Node childs = doc.getChildNodes().item(0); 
		child(childs,1);
	}
	
	/**
	 * runs the file and delete items from third level
	 * @param node1
	 * @param cont
	 * */
	public void child(Node node1,int cont){
		NodeList childs=node1.getChildNodes();
		for(int i=0;i<childs.getLength();i++){  
			Node node = childs.item(i);	
			if(node.getNodeType()==Node.ELEMENT_NODE) {
				if (cont==2) {
					node1.removeChild(node);
					i--;
				}
				if(node.hasChildNodes()){
					child(node,(cont+1));
				}
			}
		}
	}
	
	/**
	 * xml file generated
	 * */
	public void generateXml(){
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer;
		try {
			transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(doc);
			StreamResult result = new StreamResult(new File("file.xml"));
			transformer.transform(source, result);
			System.out.println("File saved!");
		} catch (TransformerConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}